package com.zk.fm.ui;

import java.util.ArrayList;
import java.util.List;

import org.ksoap2.serialization.SoapObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.zk.fm.R;
import com.zk.fm.entity.ImageAndText;
import com.zk.fm.entity.Player;
import com.zk.fm.util.CastObject;
import com.zk.fm.util.WebServiceUtil;

public class PlayersList extends Activity {
	private Button searchBtn_and;
	private Button searchBtn_or;
	private EditText searchName;
	private EditText searchTeamName;
	private Spinner chooseSpinner;
	private ListView playersList;
	private String[] searchtypes = new String[2];
	private ProgressDialog pd;
	private LinearLayout searchLayout;
	private TextView searchResult;
	private ArrayList<Player> list = new ArrayList<Player>();

	private Button refresh;
	private long id;

	private ImageAndTextListAdapter listAdapter;
	private List<ImageAndText> imageAndTexts = new ArrayList<ImageAndText>();;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.playerslist);
		searchtypes[0] = getString(R.string.playerList);
		searchtypes[1] = getString(R.string.searchPlayer);
		initViews();
		setListener();
	}

	// 1.load success 0.exception 2. no record
	private Handler mHandler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			if (id != msg.arg1) {
				return;
			}

			pd.dismiss();

			if (msg.what == 1) {
				List<Player> players = (List<Player>) msg.obj;
				imageAndTexts.clear();
				for (Player obj : players) {
					System.out.println("id  =" + obj.getId());
					String imageUrl = "http://zhengkang0301.xicp.net:8080/photo/"
							+ obj.getId() + ".jpg";
					String name = obj.getName();
					ImageAndText iat = new ImageAndText(imageUrl, name);
					imageAndTexts.add(iat);
				}
				listAdapter.notifyDataSetChanged();
				searchResult.setVisibility(View.VISIBLE);
				searchResult
						.setText(String.format(
								getString(R.string.searchResult),
								imageAndTexts.size()));
			} else if (msg.what == 2) {
				imageAndTexts.clear();
				listAdapter.notifyDataSetChanged();
				Toast.makeText(PlayersList.this, R.string.playerNotfound, 3)
						.show();
				searchResult.setVisibility(View.VISIBLE);
				searchResult.setText(String.format(
						getString(R.string.searchResult), 0));
			} else {
				Toast.makeText(PlayersList.this, R.string.loadFail, 3).show();
			}
		};
	};

	private void getPlayersByName(final String name) {
		pd.show();

		new Thread() {
			@Override
			public void run() {
				try {
					id = getId();
					List<String> l = new ArrayList<String>();
					l.add(name);
					SoapObject rpsObject = WebServiceUtil.callwebService4Obj(
							WebServiceUtil.METHOD_GETPLAYERBYNAME, l, 10000);
					if (rpsObject == null) {
						mHandler.sendEmptyMessage(2);
						return;
					}
					list.clear();
					int numOfList = rpsObject.getPropertyCount();
					for (int i = 0; i < numOfList; i++) {
						SoapObject tmpSoapObject = (SoapObject) rpsObject
								.getProperty(i);
						list.add((Player) CastObject.parseToObject(
								tmpSoapObject, Player.class));
					}

					mHandler.sendMessage(mHandler.obtainMessage(1, (int) id, 0,
							list));
				} catch (Exception e) {
					mHandler.sendMessage(mHandler.obtainMessage(0, (int) id, 0));
					e.printStackTrace();
				}
			}
		}.start();
	}

	private void getAllPlayers() {
		pd.show();

		new Thread() {

			@Override
			public void run() {
				try {
					id = getId();
					SoapObject rpsObject = WebServiceUtil.callwebService4Obj(
							WebServiceUtil.METHOD_GETALLPLAYERS, null, 10000);
					int numOfList = rpsObject.getPropertyCount();
					list.clear();
					for (int i = 0; i < numOfList; i++) {
						SoapObject tmpSoapObject = (SoapObject) rpsObject
								.getProperty(i);
						list.add((Player) CastObject.parseToObject(
								tmpSoapObject, Player.class));
					}

					mHandler.sendMessage(mHandler.obtainMessage(1, (int) id, 0,
							list));
				} catch (Exception e) {
					mHandler.sendMessage(mHandler.obtainMessage(0, (int) id, 0));
					e.printStackTrace();
				}
			}
		}.start();
	}

	private void initViews() {
		pd = new ProgressDialog(this);
		pd.setMessage(getString(R.string.loading));
		pd.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					id = -1;
				}
				return false;
			}
		});

		refresh = (Button) findViewById(R.id.refresh);

		searchResult = (TextView) findViewById(R.id.searchResult);
		searchLayout = (LinearLayout) findViewById(R.id.layout);
		playersList = (ListView) findViewById(R.id.playersList);
		searchBtn_and = (Button) findViewById(R.id.searchPlayer_and);
		searchBtn_or = (Button) findViewById(R.id.searchPlayer_or);
		searchName = (EditText) findViewById(R.id.searchName);
		searchTeamName = (EditText) findViewById(R.id.searchTeamName);
		chooseSpinner = (Spinner) findViewById(R.id.chooseSpinner);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, searchtypes);
		chooseSpinner.setAdapter(adapter);

		listAdapter = new ImageAndTextListAdapter(this, imageAndTexts,
				playersList);

		playersList.setAdapter(listAdapter);

	}

	private void setListener() {
		refresh.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				getAllPlayers();
			}
		});

		searchBtn_and.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// playerValue.setBackgroundResource(R.drawable.xiaobei);
				Toast.makeText(PlayersList.this, "db creating",
						Toast.LENGTH_SHORT).show();
			}
		});
		searchBtn_or.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				if (!clientValidate()) {
					return;
				}

				String playerName = searchName.getText().toString().trim();
				getPlayersByName(playerName);
			}
		});

		playersList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				Intent i = new Intent();
				i.setClass(PlayersList.this, PlayerProperties.class);
				Bundle mBundle = new Bundle();
				mBundle.putSerializable("player", list.get(position));
				i.putExtras(mBundle);
				startActivity(i);
			}
		});

		chooseSpinner
				.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

					public void onItemSelected(AdapterView<?> parent,
							View view, int position, long id) {
						searchResult.setVisibility(View.GONE);
						imageAndTexts.clear();
						listAdapter.notifyDataSetChanged();
						searchName.setText("");
						searchTeamName.setText("");
						switch (position) {
						case 0:
							refresh.setVisibility(View.VISIBLE);
							searchLayout.setVisibility(View.GONE);
							getAllPlayers();
							break;
						case 1:
							refresh.setVisibility(View.GONE);
							searchLayout.setVisibility(View.VISIBLE);
							break;

						default:
							break;
						}
					}

					public void onNothingSelected(AdapterView<?> arg0) {
					}
				});

	}

	protected boolean clientValidate() {
		int playerNameLength = searchName.getText().length();
		if (playerNameLength == 0) {
			searchName.requestFocus();
			searchName.setError(getString(R.string.notnull));
			return false;
		} else {
			searchName.setError(null);
		}
		// if (passwordLength == 0) {
		// password.requestFocus();
		// password.setError(getString(R.string.notnull));
		// return false;
		// } else {
		// password.setError(null);
		// }

		return true;
	}

	@Override
	protected void onRestart() {
		getAllPlayers();
		super.onRestart();
	}
}
